<?php
/**
 * 图片画册
 * AUTHOR  : zlf
 * DateTime: 2022/06/18 09:00
 */
namespace App\Api\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Api\Services\TextImageService;
use App\Http\Controllers\Api\BaseController;
use App\Api\Services\TextImageTemplatesService;
/* use App\Http\Controllers\Controller; */
class TextImageController extends BaseController
{
    /**
     * 添加文字图片画册
     * @param p_a_name 
     * @param mobile
     * @param album_cover_img
     * @param background_music
     */
    public function addTextImage(Request $request){
        
        $data = $request->all();
        
        $imgs_data=SElf::handleImgsData($request);// 处理图片画册 封面、音乐 函数
        
       if ($imgs_data['code'] === 0){
        
            $imgs_data = $imgs_data['data'];
            
        }else{
            
            return response()->json($imgs_data);
        }
        
        $data['create_time'] = time();
        $data['update_time'] = time();
        
        $data = array_merge($data,$imgs_data);
        
        $data['user_id']     = $this->getUserId();
        $data['main_id']     = $this->getMainUserId();

        $id=TextImageService::addTextImage($data);  
        if($id){
            
            $this->log('文字图片画册,添加成功', $id);
            return response()->json(['code' => 0,'msg'  => '添加成功','data' => ['pa_id'=>$id]]);
            
        }else{
         
            return response()->json(['code' => 1,'msg'  => '添加失败','data' => null]);
        }
    }
    /**
     * 删除文字图片画册
     * @param pa_ids  文字图片画册id（多个用逗号分割）
     */
    public function delTextImage(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pa_ids'          => 'required'
        ],
            [
                'pa_ids.required' => '缺少参数，文字画册id'
            ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
    
            return response()->json(['code' => 1,'msg'  => $info,'data' => '']);
        }
    
        $condition['user_id'] = $this->getUserId();
    
        $data['pa_ids'] = explode(',',$data['pa_ids']);
    
        $res = TextImageService::getTextImageInfos($condition, $data['pa_ids']);
    
        if(empty($res)){
             
            return response()->json(['code' => 1,'msg'  => '要删除的文字画册，没找到!','data' => '']);
             
        }
        
        $bool = TextImageService::delTextImage($condition,$data['pa_ids']);
      
        if($bool){
    
            foreach ($res as $tk=>$tv){
    
                if(is_file(public_path($tv['album_cover_img']))){
    
                    unlink(public_path($tv['album_cover_img']));//删除服务器中的封面
                }
    
                if(is_file(public_path($tv['background_music']))){
    
                    unlink(public_path($tv['background_music']));//删除服务器中的背景音乐
                }
            } 
            
            $t_res = TextImageTemplatesService::getTextImageTemplatesInfos($condition, $data['pa_ids']);
            
            if(!empty($t_res)){
             //删除画册对应的内容模板
             TextImageTemplatesService::delContentTempLates($condition, $data['pa_ids']);   
             
            foreach ($t_res as $tik=>$tiv){
                
                if(!empty($tiv['temp_img_video_01'])){
                    
                    $tiv['temp_img_video_01'] = explode(",",$tiv['temp_img_video_01']);
                    
                    foreach ($tiv['temp_img_video_01'] as $iv1k =>$iv1v){//删除素材1的文件
                        
                        if(is_file(public_path($iv1v))){
                    
                            unlink(public_path($iv1v));//删除服务器中素材1的文件
                        }
                    }
                  }
                  if(!empty($tiv['temp_img_video_02'])){//删除素材2的文件
                      
                      $tiv['temp_img_video_02'] = explode(",",$tiv['temp_img_video_02']);
                      
                      foreach ($tiv['temp_img_video_02'] as $iv2k =>$iv2v){
                          
                        if(is_file(public_path($iv2v))){
                    
                            unlink(public_path($iv2v));//删除服务器中素材2的文件
                        }
                    }
                  }
                }
            
            }
            
            
            $this->log('文字图片画册,删除成功', $bool);
            return response()->json(['code'=>0,'msg'=>'删除成功','data'=>'']);
             
        }else{
            return response()->json(['code'=>1,'msg'=>'删除失败','data'=>'']);
        }
    
    }
    
    /**
     * 修改文字图片画册
     * @param pa_id
     * @param p_a_name
     * @param mobile
     * @param album_cover_img
     * @param background_music
     */
    public function updateTextImage(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pa_id'          => 'required'
        ],
        [
            'pa_id.required' => '缺少参数，文字画册id'        
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {  
            
            return response()->json(['code' => 1,'msg'  => $info,'data' => '']);
        }
        
        $condition['id']      = $data['pa_id'];
        $info=TextImageService::getTextImageInfo($condition);
        $delData = [];
        if(empty($info)){
             
            return response()->json(['code'=>1,'msg'=>'异常错误！','data'=>'']);
        }
        
        if(!empty($cover_img_files = $request->file('album_cover_img'))){
            
            $res = SELF::handlePicFormat($cover_img_files,'p','封面格式,不正确！');//判断文件格式
             
            if(!empty($res)){
                 
                return $res;
            }
        
            if($cover_img_files->isValid()){
                 
                $ac_img_path = $cover_img_files->store('huace/text/album-cover-img/'.date('Y').'-'.date('m').'-'.date('d'));
                 
                $data['album_cover_img'] = '/uploads/'.$ac_img_path;
                  
                $delData[]='album_cover_img';
            }else{
                 
                return response()->json(['code' => 1,'msg' => '画册封面，上传失败！','data' => '']);
            }
        }
        
        if(!empty($cover_img_files = $request->file('background_music'))){
            
            $res = SELF::handlePicFormat($cover_img_files,'m','背景音乐格式,不正确！');//判断文件格式
             
            if(!empty($res)){
                 
                return $res;
            }
        
            if($cover_img_files->isValid()){
                 
                $ac_img_path = $cover_img_files->store('huace/text/background-music/'.date('Y').'-'.date('m').'-'.date('d'));
                 
                $data['background_music'] = '/uploads/'.$ac_img_path;

                $delData[]='background_music';
            }else{
                 
                return response()->json(['code' => 1,'msg' => '背景音乐，上传失败！','data' => '']);
                 
            }
             
        }
        
       unset($data['pa_id']);
       $bool = TextImageService::updTextImage($condition, $data); 
       
       if($bool){
           
           if(!empty($delData)){
               foreach ($delData as $dk=>$dv){
                   
                   if(is_file(public_path($info[$dv]))){
                        
                       unlink(public_path($info[$dv]));
                   }   
               }              
           }
           
           //$this->log('文字图片画册,编辑成功', $bool);
           return response()->json(['code'=>0,'msg'=>'编辑成功','data'=>'']);
           
       }else{
           return response()->json(['code'=>1,'msg'=>'编辑失败','data'=>'']);
       }
        
    }
    
    /**
     * 更新文字图片画册封面或音乐
     * @param pa_id            文字图片画册id
     * @param old_path         原封面图片或背景音乐路径
     * @param album_cover_img  画册封面
     * @param background_music 背景音乐
     */
    public function updTextImageImgMusic(Request $request){
       
        //参数验证
        $validator = Validator::make($pdata = $request->all(), [
            'pa_id'    =>'required',
            'old_path' =>'required',
        ],
            [
                'pa_id.required'   => '缺必要参数，文字画册id',
                'old_path.required'=> '原画册封面or背景音乐路径，不能为空',
            ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
    
            return response()->json(['code' => 1,'msg'  => $info,'data' => '']);
        }
    
            $flag = 'album_cover_img';
            
        if(!empty($request->file('background_music'))){
            
            $flag = 'background_music';
        }
            $data[$flag] = "";
            
        if(!empty($cover_img_files = $request->file($flag))){
            
            $res = SELF::handlePicFormat($cover_img_files,'p','封面格式,不正确！');//判断文件格式
             
            if(!empty($res)){
                 
                return $res;
            }
            if($cover_img_files->isValid()){
                 
                $ac_img_path = $cover_img_files->store('huace/text/album-cover-img/'.date('Y').'-'.date('m').'-'.date('d'));
                 
                $data[$flag] = '/uploads/'.$ac_img_path;
    
            }else{
                 
                return response()->json(['code' => 1,'msg' => '画册封面，上传失败！','data' => '']);
            }
        }
    
        if(!empty($cover_img_files = $request->file($flag))){
    
            $res = SELF::handlePicFormat($cover_img_files,'m','背景音乐格式,不正确！');//判断文件格式
             
            if(!empty($res)){
                 
                return $res;
            }
                        
            if($cover_img_files->isValid()){
                 
                $ac_img_path = $cover_img_files->store('huace/text/background-music/'.date('Y').'-'.date('m').'-'.date('d'));
                 
                $data[$flag] = '/uploads/'.$ac_img_path;
            }else{
                 
                return response()->json(['code' => 1,'msg' => '背景音乐，上传失败！','data' => '']);
                 
            }
             
        }
        if(!empty($data[$flag])){
            
            $condition['id']      = $pdata['pa_id'];
            $condition['user_id'] = $this->getUserId();
        
            $bool = TextImageService::updTextImage($condition,$data);
        
            if($bool){
        
                if(is_file(public_path($pdata['old_path']))){
        
                    unlink(public_path($pdata['old_path']));
                }
                $this->log('更新文字图片画册封面或音乐,更新成功', $bool);
                return response()->json(['code'=>0,'msg'=>'更换成功','data'=>$data]);
        
            }
        }
        
        return response()->json(['code'=>1,'msg'=>'更换失败','data'=>'']);
    
    }
    
    /**
     * 查询文字画册列表
     * @param curr_page 页码
     */
    public function getTextImageList(Request $request){

        $condition['ti.user_id'] = $this->getUserId();

        $currentPage = !empty($request->input('curr_page'))?$request->input('curr_page'):1;
       $pageSize = !empty($request->input('page_size'))?$request->input('page_size'):20;
        $list        = TextImageService::getTextImageList($condition, $currentPage,$pageSize);
        
        if(!empty($list['data'])){
            
               foreach ($list['data'] as $k=>$val){
    
                $list['data'][$k]['create_time']=date('Y-m-d H:i:s',$val['create_time']);
                $list['data'][$k]['update_time']=date('Y-m-d H:i:s',$val['update_time']);
                       
             
               }
           }
       
        $this -> log('文字图片画册，查询成功', $list);
        
        return response()->json(['code'=>0,'msg'=>'查询成功','data'=>$list]);
        
        
    }
     
     /**
      * 查询文字画册信息
      * @param pa_id 文字画册id
      */
    public function getTextImageInfo(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pa_id'          => 'required'
        ],
            [
                'pa_id.required' => '缺少参数，文字画册id'
            ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
        
            return response()->json(['code' => 1,'msg'  => $info,'data' => '']);
        }
        
        $condition['id']      = $data['pa_id'];
        $condition['user_id'] = $this->getUserId();
        
        $info = TextImageService::getTextImageInfo($condition);
        
        if(!empty($info)){
            $this->log('查询文字画册信息,查询成功', $info);
            return response()->json(['code' =>0,'msg'  => '查询成功','data' => $info]);
        }else{
            
            return response()->json(['code' => 1,'msg'  => '查询失败','data' => '']);
        }
        
    }
    /**
     * 处理图片画册 封面、音乐 函数
     *
     */
    static public function handleImgsData($request){
         
        $data = [];     
        $data['album_cover_img']  = "";
        $data['background_music'] = "";
         
        if(!empty($cover_img_files = $request->file('album_cover_img'))){
            
            $res = SELF::handlePicFormat($cover_img_files,'p','封面格式,不正确！');//判断文件格式
             
            if(!empty($res)){
                 
                return $res;
            }
    
            if($cover_img_files->isValid()){
                 
                $ac_img_path = $cover_img_files->store('huace/text/album-cover-img/'.date('Y').'-'.date('m').'-'.date('d'));
                 
                $data['album_cover_img'] = '/uploads/'.$ac_img_path;
            }else{
                 
                return [
                    'code' => 1,
                    'msg' => '画册封面，上传失败！',
                    'data' => ''
                ];
                 
            }
             
        }elseif(!empty($request->input('album_cover_img'))){
    
            $data['album_cover_img'] = $request->input('album_cover_img');
        }
         
        if(!empty($music_files = $request->file('background_music'))){
             
            $res = SELF::handlePicFormat($music_files,'m','音乐格式,不正确！');//判断文件格式
             
            if(!empty($res)){
                 
                return $res;
            }
            
            if($music_files->isValid()){
                 
                $music_path = $music_files->store('huace/text/background-music/'.date('Y').'-'.date('m').'-'.date('d'));
                 
                $data['background_music'] = '/uploads/'.$music_path;
            }else{
    
                return [
                    'code' => 1,
                    'msg' => '背景音乐，上传失败！',
                    'data' => ''
                ];
  
            }
             
        }elseif(!empty($request->input('background_music'))){
             
            $data['background_music'] = $request->input('background_music');
        }

        return [
            'code' => 0,
            'msg' => 'success',
            'data' => $data,
        ];
    }
        
    /**
     * 处理图片和视频格式
     */
    static public function handlePicFormat($files,$flag,$msg){
 
        $pic_video_format = 'mp3,aac,wav,wma,cda,flac,m4a,mid,mka,mp2,mpa,mpc,ape,ofr,ogg,ra,wv,ac3,dts,
                            flash,mpeg,mpeg-2,mpeg-4,midi,wmv,asf,asx,rm,rmvb,mp4,3gp,mov,m4v,avi,dat,mkv,flv,vob,
                            bmp,jpg,png,tif,gif,pcx,tga,exif,fpx,svg,psd,cdr,pcd,dxf,
                            ufo,eps,ai,raw,wmf,webp,avif,apng';
        
        $pic_format       = 'bmp,jpg,png,tif,gif,pcx,tga,exif,fpx,svg,psd,cdr,pcd,dxf,ufo,eps,ai,raw,wmf,webp,avif,apng';
        
        $music_format     = 'mp3,aac,wav,wma,cda,flac,m4a,mid,mka,mp2,mpa,mpc,ape,ofr,ogg,ra,wv,ac3,dts';
        
        $ext = $files->extension();
        
        $ext = strtolower($ext);
        
        if($flag == 'm'){
        
            $pic_video_format_arr = explode(',',$music_format);
        
        }elseif($flag == 'p'){
            
            $pic_video_format_arr = explode(',',$pic_format);
            
        }else{
            
            $pic_video_format_arr = explode(',',$pic_video_format);
        }
         
        if (!in_array($ext, $pic_video_format_arr)) {
             
            return ['code' => 1,'msg' => $msg,'data' => ''];die;
        }
         
    }
}
